package bid

import (
	"context"
	"errors"
	dto "git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/dto/business_opportunity"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/repository/business_opportunity"
	pb "git.mycaigou.com/gfyx/micro-gfyx-api/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/business_opportunity"
	"strings"
)

type bidService struct {
	bidRepo business_opportunity.BidRepositoryIface
}

func NewBidService(bidRepo business_opportunity.BidRepositoryIface) BidServiceIface {
	return &bidService{
		bidRepo: bidRepo,
	}
}

// SearchBid 找招中标
func (s *bidService) SearchBid(ctx context.Context, request *dto.SearchBidRequest, scene int) (*dto.SearchBidResponse, error) {
	data, err := s.bidRepo.SearchBid(ctx, &pb.SearchBidRequest{
		Page:             request.Page,
		PageSize:         request.PageSize,
		OrganizingCode:   request.OrganizingCode,
		Keyword:          request.Keyword,
		SearchType:       request.SearchType,
		AreaCode:         request.AreaCode,
		CompanyAreaCode:  request.CompanyAreaCode,
		Type:             request.Type,
		DataSourceCode:   request.DataSourceCode,
		CompanyType:      request.CompanyType,
		CompanyLabel:     request.CompanyLabel,
		PublishDateStart: request.PublishDateStart,
		PublishDateEnd:   request.PublishDateEnd,
		EndDateStart:     request.EndDateStart,
		EndDateEnd:       request.EndDateEnd,
		Id:               request.Id,
		SubId:            request.SubId,
	})
	resp := &dto.SearchBidResponse{
		MaxNum: 5000,
		List:   make([]*dto.SearchBidItem, 0),
	}
	if err != nil {
		return resp, err
	}
	if data != nil {
		resp.Total = data.Total
		for _, v := range data.List {
			row := s.dealBidDetail(ctx, v)
			if scene == 2 && row.Type != "" {
				row.Type += "阶段"
			}
			resp.List = append(resp.List, row)
		}
	}
	return resp, nil
}

func (s *bidService) ExportSearchBid(ctx context.Context, request *dto.ExportSearchBidRequest) (*dto.ExportSearchBidResponse, error) {
	resp, err := s.bidRepo.ExportSearchBid(ctx, &pb.ExportSearchBidRequest{
		OrganizingCode:   request.OrganizingCode,
		Keyword:          request.Keyword,
		SearchType:       request.SearchType,
		AreaCode:         request.AreaCode,
		CompanyAreaCode:  request.CompanyAreaCode,
		Type:             request.Type,
		DataSourceCode:   request.DataSourceCode,
		CompanyType:      request.CompanyType,
		CompanyLabel:     request.CompanyLabel,
		PublishDateStart: request.PublishDateStart,
		PublishDateEnd:   request.PublishDateEnd,
		EndDateStart:     request.EndDateStart,
		EndDateEnd:       request.EndDateEnd,
		Id:               request.Id,
		SubId:            request.SubId,
	})
	if err != nil {
		return nil, err
	}
	if resp == nil {
		return nil, errors.New("导出失败")
	}

	return &dto.ExportSearchBidResponse{
		JobId: resp.JobId,
	}, nil
}

func (s *bidService) dealBidDetail(ctx context.Context, item *pb.BidData) *dto.SearchBidItem {
	row := &dto.SearchBidItem{
		Id:                             item.Id,
		Title:                          item.Title,
		DeveloperName:                  item.DeveloperName,
		OrganizingCode:                 item.OrganizingCode,
		TopCompanyName:                 item.TopCompanyName,
		TopCompanyOrganizingCode:       item.TopCompanyOrganizingCode,
		CompanyProvince:                item.CompanyProvince,
		CompanyProvinceCode:            item.CompanyProvinceCode,
		CompanyCity:                    item.CompanyCity,
		CompanyCityCode:                item.CompanyCityCode,
		PublishDate:                    item.PublishDate,
		EndDate:                        item.EndDate,
		DataSource:                     item.DataSource,
		DataSourceCode:                 item.DataSourceCode,
		PurchaseContactCnt:             item.PurchaseContactCnt,
		CoopSupplierContactCnt:         item.CoopSupplierContactCnt,
		FirstWinbidSupplierContactCnt:  item.FirstWinbidSupplierContactCnt,
		SecondWinbidSupplierContactCnt: item.SecondWinbidSupplierContactCnt,
		ThirdWinbidSupplierContactCnt:  item.ThirdWinbidSupplierContactCnt,
		ContactCnt:                     item.ContactCnt, //联系人数量(总计)
		TitleHL:                        item.Title_HL,
		DeveloperNameHL:                item.DeveloperName_HL,
		XScore:                         item.XScore,
		CompanyType:                    item.CompanyType,
		Type:                           item.Type,
		OpptyStatus:                    item.OpptyStatus,
	}
	//企业标签
	if item.CompanyLabelArr != "" {
		row.CompanyLabelArr = strings.Split(item.CompanyLabelArr, ",")
	} else {
		row.CompanyLabelArr = make([]string, 0)
	}

	//省份城市
	if item.ProjectProvince != nil {
		for _, v := range item.ProjectProvince {
			row.ProjectProvince = append(row.ProjectProvince, dto.ProvinceAndCity{
				Province:     v.Province,
				ProvinceCode: v.ProvinceCode,
				City:         v.City,
				CityCode:     v.CityCode,
			})
		}
	} else {
		row.ProjectProvince = make([]dto.ProvinceAndCity, 0)
	}
	//中标单位
	if item.SupplierList == nil || len(item.SupplierList) == 0 {
		row.SupplierList = make([]*dto.WinBidSupplier, 0)
	} else {
		for _, v := range item.SupplierList {
			row.SupplierList = append(row.SupplierList, &dto.WinBidSupplier{
				SupplierName:           v.SupplierName,
				SupplierNameHL:         v.SupplierName_HL,
				SupplierOrganizingCode: v.SupplierOrganizingCode,
			})
		}
	}
	return row
}

// FuzzySearchBid 模糊搜索招中标
func (s *bidService) FuzzySearchBid(ctx context.Context, request *dto.FuzzySearchBidRequest) ([]*dto.FuzzySearchBidData, error) {
	data, err := s.bidRepo.FuzzySearchBid(ctx, &pb.FuzzySearchBidRequest{
		Keyword:    request.Keyword,
		SearchType: request.SearchType,
	})
	res := make([]*dto.FuzzySearchBidData, 0)
	if err != nil {
		return res, err
	}
	if data != nil {
		for _, v := range data.List {
			res = append(res, &dto.FuzzySearchBidData{
				TitleHL: v.TitleHL,
				Title:   v.Title,
			})
		}
	}
	return res, nil
}

// BidDetail 招标详情
func (s *bidService) BidDetail(ctx context.Context, request *dto.BidDetailRequest) (*dto.BidDetailResponse, error) {
	data, err := s.bidRepo.BidDetail(ctx, &pb.BidDetailRequest{
		Id: request.Id,
	})
	resp := &dto.BidDetailResponse{}
	if err != nil {
		return resp, err
	}
	if data != nil {
		resp.Id = data.Id
		resp.BiddingServiceCategory = data.BiddingServiceCategory
		resp.ContentID = data.ContentId
		resp.CreatedAt = data.CreatedAt
		resp.DataSourceCode = data.DataSourceCode
		resp.DataSource = data.DataSource
		resp.DeveloperName = data.DeveloperName
		resp.EndTime = data.EndTime
		resp.IsMatchMaster = data.IsMatchMaster
		resp.OrganizingCode = data.OrganizingCode
		resp.PublishTime = data.PublishTime
		resp.Title = data.Title
		resp.TopOrganizingCode = data.TopOrganizingCode
		resp.TopDeveloperName = data.TopDeveloperName
		resp.TopCompanyType = data.TopCompanyType
		resp.TopParentCompanyType = data.TopParentCompanyType
		resp.Url = data.Url
		resp.Uid = data.Uid
		resp.WebsiteName = data.WebsiteName
		resp.Detail = data.Detail
		resp.ContentHtml = data.ContentHtml
		resp.OpptyStatus = data.OpptyStatus
		resp.OwerMobileVisible = data.OwerMobileVisible
		resp.PurchaseAmount = data.PurchaseAmount
		if resp.ContentHtml == "" && resp.Detail == "" {
			resp.ContentHtml = "请点击右上角查看原文"
		}
		//省份城市
		if data.ProjectProvince != nil {
			for _, v := range data.ProjectProvince {
				resp.ProjectProvince = append(resp.ProjectProvince, dto.ProvinceAndCity{
					Province:     v.Province,
					ProvinceCode: v.ProvinceCode,
					City:         v.City,
					CityCode:     v.CityCode,
				})
			}
		} else {
			resp.ProjectProvince = make([]dto.ProvinceAndCity, 0)
		}
		//关联公司
		resp.RelatedCompany = make([]dto.RelatedCompany, 0)
		if data.RelatedCompany != nil {
			for _, v := range data.RelatedCompany {
				resp.RelatedCompany = append(resp.RelatedCompany, dto.RelatedCompany{
					CompanyName:    v.CompanyName,
					OrganizingCode: v.OrganizingCode,
					Role:           v.Role,
					Labels:         v.Labels,
				})
			}
		}
		//关联负责人
		resp.RelatedOwner = make([]dto.RelatedOwner, 0)
		if data.RelatedOwner != nil {
			for _, v := range data.RelatedOwner {
				resp.RelatedOwner = append(resp.RelatedOwner, dto.RelatedOwner{
					Name:   v.Name,
					Mobile: v.Mobile,
					Role:   v.Role,
				})
			}
		}

	}
	return resp, nil
}

// BidDetailMobile 招标详情-手机号明文
func (s *bidService) BidDetailMobile(ctx context.Context, request *dto.BidDetailMobileRequest) (*dto.BidDetailMobileResponse, error) {
	data, err := s.bidRepo.BidDetailMobile(ctx, &pb.BidDetailMobileRequest{
		Id: request.Id,
	})
	resp := &dto.BidDetailMobileResponse{}
	if err != nil {
		return resp, err
	}
	if data != nil {
		resp.Id = data.Id
		resp.OwerMobile = data.OwerMobile
		resp.AgentOwerMobile = data.AgentOwerMobile
	}
	return resp, nil
}

// WinBidDetail 中标详情
func (s *bidService) WinBidDetail(ctx context.Context, request *dto.WinBidDetailRequest) (*dto.WinBidDetailResponse, error) {
	data, err := s.bidRepo.WinBidDetail(ctx, &pb.WinBidDetailRequest{
		Id: request.Id,
	})
	resp := &dto.WinBidDetailResponse{}
	if err != nil {
		return resp, err
	}
	if data != nil {
		resp.Id = data.Id
		resp.AgentAddress = data.AgentAddress
		resp.AgentContact = data.AgentContact
		resp.AgentPhone = data.AgentPhone
		resp.AgentUnit = data.AgentUnit
		resp.BidMaxLimitPrice = data.BidMaxLimitPrice
		resp.Category = data.Category
		resp.City = data.City
		resp.CityCode = data.CityCode
		resp.ContentId = data.ContentId
		resp.DeveloperTop100Label = data.DeveloperTop_100Label
		resp.FirstWinbidPrice = data.FirstWinbidPrice
		resp.FirstWinbidSupplierAddress = data.FirstWinbidSupplierAddress
		resp.FirstWinbidSupplierName = data.FirstWinbidSupplierName
		resp.FirstWinbidSupplierOrganizingCode = data.FirstWinbidSupplierOrganizingCode
		resp.LinkUrl = data.LinkUrl
		resp.NewAreaExpandLabel = data.NewAreaExpandLabel
		resp.NewDecorateExpandLabel = data.NewDecorateExpandLabel
		resp.NewLandUsageExpandLabel = data.NewLandUsageExpandLabel
		resp.OpenTime = data.OpenTime
		resp.OrganizingCode = data.OrganizingCode
		resp.OwerAddress = data.OwerAddress
		resp.OwerContact = data.OwerContact
		resp.OwerPhone = data.OwerPhone
		resp.OwerUnit = data.OwerUnit
		resp.PriceGtAvgLabel = data.PriceGtAvgLabel
		resp.ProjectAddress = data.ProjectAddress
		resp.ProjectName = data.ProjectName
		resp.ProjectNumber = data.ProjectNumber
		resp.ProjectOwer = data.ProjectOwer
		resp.Province = data.Province
		resp.ProvinceCode = data.ProvinceCode
		resp.PublishTime = data.PublishTime
		resp.SecondWinbidPrice = data.SecondWinbidPrice
		resp.SecondWinbidSupplierAddress = data.SecondWinbidSupplierAddress
		resp.SecondWinbidSupplierName = data.SecondWinbidSupplierName
		resp.SecondWinbidSupplierOrganizingCode = data.SecondWinbidSupplierOrganizingCode
		resp.SecondWinbidSupplierPhone = data.SecondWinbidSupplierPhone
		resp.Source = data.Source
		resp.SourceSub = data.SourceSub
		resp.ThirdWinbidPrice = data.ThirdWinbidPrice
		resp.ThirdWinbidSupplierAddress = data.ThirdWinbidSupplierAddress
		resp.ThirdWinbidSupplierName = data.ThirdWinbidSupplierName
		resp.ThirdWinbidSupplierOrganizingCode = data.ThirdWinbidSupplierOrganizingCode
		resp.ThirdWinbidSupplierPhone = data.ThirdWinbidSupplierPhone
		resp.Title = data.Title
		resp.Type = data.Type
		resp.WebsiteName = data.WebsiteName
		resp.ContentHtml = data.ContentHtml
		resp.OpptyStatus = data.OpptyStatus
		//关联公司
		resp.RelatedCompany = make([]dto.RelatedCompany, 0)
		if data.RelatedCompany != nil {
			for _, v := range data.RelatedCompany {
				resp.RelatedCompany = append(resp.RelatedCompany, dto.RelatedCompany{
					CompanyName:    v.CompanyName,
					OrganizingCode: v.OrganizingCode,
					Role:           v.Role,
					Labels:         v.Labels,
				})
			}
		}
	}
	return resp, nil
}
